package me.helllp.book.concurrent.ch04;

import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试ThreadLocal的GC回收
 * 
 * @author Administrator
 *
 */
public class ThreadLocalDemoGC {
	static volatile ThreadLocal<SimpleDateFormat> t1 = new ThreadLocal<SimpleDateFormat>(){
		protected void finalize() throws Throwable {
			System.out.println(this.toString() + " 被回收了！");
		};
	};
	
	static volatile CountDownLatch cd = new CountDownLatch(10000);
	
	public static class ParseDate implements Runnable{
		int i = 0;
		
		public ParseDate(int i){
			this.i = i;
		}
		
		@Override
		public void run() {
			try {
				if(t1.get() == null){
					t1.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"){
						private static final long serialVersionUID = 1L;

						@Override
						protected void finalize() throws Throwable {
							System.out.println(this.toString() + " 被回收了！");
						}
					});
				}
				
				t1.get().parse("2018-01-23 15:34:" + i % 60);
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				cd.countDown();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		ExecutorService exec = Executors.newFixedThreadPool(10);
		
		for(int i=0; i<10000; i++){
			exec.execute(new ParseDate(i));
		}
		
		cd.await();
		System.out.println("任务执行完成！");
		t1 = null;
		System.gc();
		System.out.println("第一次GC执行完成！");
		t1 = new ThreadLocal<SimpleDateFormat>();
		
		cd = new CountDownLatch(10000);
		
		for(int i=0; i< 10000; i++){
			exec.execute(new ParseDate(i));
		}
		cd.await();
		
		Thread.sleep(1000);
		System.gc();
		System.out.println("第二次GC执行完成！");
	}
}
